<template>
  <a-tree-select
    v-model:modelValue="value"
    :loading="loading"
    :allow-search="true"
    :allow-clear="true"
    :data="treeData"
    placeholder="请选择岗位"
    :multiple="multiple"
    :tree-check-strictly="treeCheckStrictly"
    :field-names="{
      key: 'id',
      title: 'name',
      children: 'children',
    }"
  ></a-tree-select>
</template>

<script lang="ts" setup>
  import { ref, computed, defineProps, defineEmits, PropType } from 'vue';
  import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import useLoading from '@/hooks/loading';
  import { PositionVo, selectPagePosition } from '@/api/position';
  import tree from '@/utils/tree';

  const { loading, setLoading } = useLoading();
  const props = defineProps({
    modelValue: {
      type: String as PropType<string | string[]>,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    treeCheckStrictly: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  });
  const resData = ref<PositionVo[]>([]);
  const emit = defineEmits(['update:modelValue', 'change']);
  const value = computed({
    get() {
      return props.modelValue;
    },
    set(val) {
      emit('update:modelValue', val);
      emit(
        'change',
        val,
        props.multiple
          ? resData.value.filter((item) => val.includes(item.id || ''))
          : resData.value.find((item) => item.id === val)
      );
    },
  });

  const treeData = ref<TreeNodeData[]>([]);
  const fetchData = async () => {
    setLoading(true);
    try {
      const params = {
        code: '', // 岗位编码
        leaderPositionId: '', // 岗位的上级领导岗位
        level: '', // 岗位级别
        levelName: '', // 岗位等级名称
        name: '', // 岗位名称
        simpleName: '', // 岗位简称
        type: '', // 岗位类型
      };
      const { data } = await selectPagePosition(params);
      resData.value = data;
      treeData.value = tree.toTree(data, 'id', 'leaderPositionId');
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  fetchData();
</script>
